package com.bawei.module_play

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_base.RoutePath
import com.bawei.lib_common.mvi.BaseMviActivity
import com.bawei.module_play.adapter.PlayListAdapter
import com.bawei.module_play.adapter.PlayLoveAdapter
import com.bawei.module_play.adapter.PlayPageAdapter
import com.bawei.module_play.databinding.ActivityPlayBinding
import com.bawei.module_play.entriy.AuthorEntriy
import com.bawei.module_play.entriy.CommendEntity
import com.bawei.module_play.entriy.CommentEntriyItem
import com.bawei.module_play.entriy.SimpleVideoEntity
import com.bawei.module_play.entriy.TabEntriy
import com.bawei.module_play.intent.PlayVideoIntent
import com.bawei.module_play.state.PlayVideoState
import com.bawei.module_play.vm.PlayViewModel
import com.bumptech.glide.Glide
import com.example.image.glide.GlideImgLoader
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.luck.picture.lib.utils.ToastUtils
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import master.flame.danmaku.controller.DrawHandler
import master.flame.danmaku.danmaku.model.BaseDanmaku
import master.flame.danmaku.danmaku.model.DanmakuTimer
import master.flame.danmaku.danmaku.model.IDanmakus
import master.flame.danmaku.danmaku.model.android.DanmakuContext
import master.flame.danmaku.danmaku.model.android.Danmakus
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser

@AndroidEntryPoint
@Route(path = RoutePath.PATH_PLAY_PAGE)
class PlayActivity : BaseMviActivity<ActivityPlayBinding>() {
    @Autowired
    @JvmField var videoPath: String = ""
    @Autowired
    @JvmField var userId: String = ""
    @Autowired
    @JvmField var channelId: String = ""
    @Autowired
    @JvmField var typeId: Int = -1
    @Autowired
    @JvmField var moduleType: Int = 0 //默认从首页进入
    @Autowired
    @JvmField var itemId: String = ""
    @Autowired
    @JvmField var title: String = ""

    //弹幕
    private lateinit var mDanmuContent:DanmakuContext
    //viewmodel
    private val mViewModel:PlayViewModel by viewModels()

    //推荐视频
    private var playloveVideoList= mutableListOf<SimpleVideoEntity>()
    private lateinit var playloveadapter: PlayLoveAdapter

    //评论列表
    private var commVideoList= mutableListOf<CommentEntriyItem>()
    private lateinit var commlistadapter: PlayListAdapter


    override fun getLayoutId(): Int {
        return  R.layout.activity_play
    }

    override fun initViews() {
        intent.extras?.apply {
            videoPath = getString("videoPath").toString()
            userId = getString("userId").toString()
            channelId = getString("channelId").toString()
            itemId = getString("itemId").toString()
            typeId = getInt("typeId")
            moduleType = getInt("moduleType")
            title=getString("title").toString()
        }
        mDataNBinding.tvVideoDesc.text=title

        //推荐视频适配器
        playloveadapter= PlayLoveAdapter(playloveVideoList)
        mDataNBinding.rvUserVideo.adapter=playloveadapter

        commlistadapter=PlayListAdapter(commVideoList)


        //使用GSY播放视频
        mDataNBinding.videoPlayer?.apply {
            setUp(videoPath,true,"")
            backButton.visibility=View.GONE
            fullscreenButton.setOnClickListener {
                startWindowFullscreen(this.context,false,true)
            }
        }

        //点击弹幕按钮事件
        mDataNBinding.ivDanmuImg.setOnClickListener {
            mDataNBinding.llDanmuLayout.visibility=View.VISIBLE
        }

        //发送弹幕按钮事件
        mDataNBinding.ivDanmuSend.setOnClickListener {
            //检验弹幕内容
            var danmuContent=mDataNBinding.etDanmuInput.editableText.toString()
            if(danmuContent.isNotEmpty()){
                sendVideoDanmu(danmuContent)
            }
        }
        //初始化弹幕
        initDanmu()

        //点击弹出窗体
        mDataNBinding.llCoin2.setOnClickListener {
            //设置布局
            val view=LayoutInflater.from(this).inflate(R.layout.popuwindews_item,null)
            //定义popuwindows
            var popuwindows=PopupWindow(this)
            popuwindows.contentView=view
            popuwindows.isOutsideTouchable=true
            popuwindows.isFocusable=true
            popuwindows.width=WindowManager.LayoutParams.MATCH_PARENT
            popuwindows.height=1000
            popuwindows.showAtLocation(mDataNBinding.llCoin2,Gravity.BOTTOM,0,0)
            popuwindows.setOnDismissListener {
                popuwindows.dismiss()
            }
            //获取布局中的rv列表
            var rv=view.findViewById<RecyclerView>(R.id.windowrv)
            //评论适配器
            rv.adapter = commlistadapter

            //获取弹窗中的发送按钮
            var send=view.findViewById<ImageView>(R.id.iv_danmu_send)
            var comment=view.findViewById<EditText>(R.id.et_danmu_input)
            send.setOnClickListener {
                lifecycleScope.launch {
                    mViewModel.channel.send(PlayVideoIntent.PublishVideoComment(CommendEntity(
                        0,
                        comment.text.toString(),
                        "",
                        0,
                        0,
                        itemId.toLong(),
                        "梦琪",
                        emptyList(),
                        20,
                        6486,
                        ""
                    )))
                }
                comment.setText("")
            }

        }
    }

    override suspend fun sendViewIntent() {
        super.sendViewIntent()
        mViewModel.channel.send(PlayVideoIntent.LoadAuthorInfo(userId))
        mViewModel.channel.send(PlayVideoIntent.LoadRecommendSimpleVideo(1,10))
        mViewModel.channel.send(PlayVideoIntent.LoadCommentByUserId(0,itemId))

    }
    override suspend fun collectUIState() {
        mViewModel.uiStateFlow.collect{
            when(it){
                is PlayVideoState.LoadAuthorSuccess ->updataPageDate(it.entity)
                is PlayVideoState.LoadAuthorFail ->{
                    ToastUtils.showToast(this,"作者详情加载失败")
                }
                is PlayVideoState.LoadSimpleVideoSuccess ->updataSimpleVideo(it.list)
                is PlayVideoState.LoadSimpleVideoFail ->{
                    ToastUtils.showToast(this,"推荐视频加载失败")
                }
                is PlayVideoState.LoadVideoCommentSuccess -> updataPageDatecomm(it.list)
                is PlayVideoState.LoadVideoCommentFail -> {
                    ToastUtils.showToast(this,"加载失败")
                }
                is PlayVideoState.PublishVideoCommentSuccess -> {
                    ToastUtils.showToast(this,"${it.content}")
                    lifecycleScope.launch {
                        mViewModel.channel.send(PlayVideoIntent.LoadCommentByUserId(0,itemId))
                    }
                }
                is PlayVideoState.PublishVideoCommentFail -> {
                    ToastUtils.showToast(this,"评论失败")
                }
                else->{

                }
            }
        }
    }

    private fun updataPageDatecomm(list: List<CommentEntriyItem>){
        commVideoList.addAll(list)
        commlistadapter.notifyDataSetChanged()
    }


    private fun updataPageDate(list: AuthorEntriy){
        GlideImgLoader.loadCircleImage(mDataNBinding.ivUserIcon.context,list.avatar_url,mDataNBinding.ivUserIcon)
        mDataNBinding.tvUserName.text=list.name
        mDataNBinding.tvUserDesc.text=list.description
        mDataNBinding.tvLikeCount.text=list.followerscount+"万喜欢"
        mDataNBinding.tvSendTime.text="发布时间 : "+list.ctime
    }

    private fun updataSimpleVideo(list: List<SimpleVideoEntity>){
        playloveVideoList.addAll(list)
        playloveadapter.notifyDataSetChanged()
    }


    private fun initDanmu(){
        //创建上下文
        mDanmuContent= DanmakuContext.create()
        //准备弹幕
        mDataNBinding.danmuView.apply {
            //准备
            prepare(object :BaseDanmakuParser(){
                override fun parse(): IDanmakus {
                    return Danmakus()
                }

            },mDanmuContent)

            //设置一些回调问题
            setCallback((object :DrawHandler.Callback{
                override fun prepared() {

                }

                override fun updateTimer(timer: DanmakuTimer?) {

                }

                override fun danmakuShown(danmaku: BaseDanmaku?) {

                }

                override fun drawingFinished() {

                }

            }))
        }
    }

    /**
     * 发送弹幕
     */
    private fun sendVideoDanmu(content:String){
        mDataNBinding.danmuView.clear()

        //封装弹幕实体
        var danmuEntity = mDanmuContent.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL).apply {
            text = content
            textSize = 50f
            textColor = Color.YELLOW
            padding = 10
            time = 500 //延迟时间

        }
        //将弹幕实体添加到弹幕组件中
        mDataNBinding.danmuView.apply {
            addDanmaku(danmuEntity)
            start()
        }

        //清理输入框
        mDataNBinding.etDanmuInput.setText("")
        mDataNBinding.llDanmuLayout.visibility = View.GONE

    }







    override fun onResume() {
        super.onResume()
        mDataNBinding?.videoPlayer?.startPlayLogic()
    }

    override fun onPause() {
        super.onPause()
        mDataNBinding?.videoPlayer?.onVideoPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mDataNBinding?.videoPlayer?.release()
    }


}